#!/bin/sh

kloxopath='/usr/local/lxlabs/kloxo'

yum -y install python27 python27-devel python27-pip python27-setuptools \
	python27-virtualenv >/dev/null 2>&1

yum install -y python python-devel python-virtualenv >/dev/null 2>&1

yum remove -y python27-tools >/dev/null 2>&1

# these would be installed automaticly by the client but I prefer to do it myself
yum -y install gcc dialog augeas-libs openssl-devel libffi-devel \
	redhat-rpm-config ca-certificates >/dev/null 2>&1

# install let
yum -y install git
cd ${kloxopath}
if [ -d ${kloxopath}/letsencrypt ] ; then
	'rm' -rf ${kloxopath}/letsencrypt >/dev/null 2>&1
	'rm' -rf /root/.local/share/letsencrypt >/dev/null 2>&1
fi

if [ -d ${kloxopath}/certbot ] ; then
	'rm' -rf ${kloxopath}/certbot >/dev/null 2>&1
	'rm' -rf /root/.local/share/certbot >/dev/null 2>&1
fi

wget https://github.com/certbot/certbot/archive/master.zip -O master.zip \
	--no-check-certificate >/dev/null 2>&1

unzip -oq master.zip >/dev/null 2>&1
'mv' -f certbot-master certbot >/dev/null 2>&1
'rm' -f master.zip >/dev/null 2>&1

ln -sf ${kloxopath}/certbot/letsencrypt-auto /usr/bin/letsencrypt-auto >/dev/null 2>&1
ln -sf ${kloxopath}/certbot/certbot-auto /usr/bin/certbot-auto >/dev/null 2>&1
ln -sf ${kloxopath}/certbot/py26reqs.txt /usr/bin/py26reqs.txt >/dev/null 2>&1

${kloxopath}/certbot/letsencrypt-auto --version

cronfile='/var/spool/cron/root'

'cp' -f ${kloxopath}/file/letsencrypt/letsencrypt-cron.sh \
	${kloxopath}/certbot/letsencrypt-cron.sh \
	>/dev/null 2>&1

if [ -f ${cronfile} ] ; then
	if [ "$(cat ${cronfile}|grep 'letsencrypt-cron.sh')" != "" ] ; then
		## ST -- remove old cron
		sed -i '/letsencrypt\-cron\.sh/d' ${cronfile}
	fi

	## ST -- use it because priority for acme.sh if exists
	if [ ! -f /root/.acme.sh/acme.sh ] ; then
		if [ "$(cat ${cronfile}|grep 'acme-cron.sh')" != "" ] ; then
			## ST -- remove old cron
			sed -i '/acme\-cron\.sh/d' ${cronfile}
		fi

		cmd="sh ${kloxopath}/certbot/letsencrypt-cron.sh"
		crontab -l | { cat; echo "0 0 1 * * ${cmd} >/dev/null 2>&1"; } | crontab -
	fi
fi

cd /
